#!/usr/bin/python

from Tkinter import *

import sys
import types
from qpid.messaging import *
from amqp import RoutingKey

def getProtoClass(packageName, messageName):
   
   module = __import__(packageName + '.' + messageName + '_pb2',
                    globals(), locals(), [messageName])
   return getattr(module, messageName)

def printMsg(msg):
   import datetime
   for (fd, value) in msg.ListFields():
      if fd.name[-4:] == '_lct':
         continue
         
      print fd.name , ':',
      if fd.name[-4:] == '_utc':
         print datetime.datetime.fromtimestamp(int(value)/1000000) 
      else:
         print value
         
   print

import threading

class Receiver(threading.Thread):
   def __init__(self, ip, port, protoSrc):
      threading.Thread.__init__(self)
      self.__ip = ip
      self.__port = port
      self.__protoSrc = protoSrc
      self.__exit = False
      
   def run(self):
      if sys.path.count(self.__protoSrc) == 0:
         sys.path.append(self.__protoSrc)

      broker = '%s:%s' % (self.__ip, self.__port)
      address = 'amq.topic'

      connection = Connection(broker)
      try:
         connection.open()
         session = connection.session()
   
         receiver = session.receiver(address)
   
         count = 0
         while not self.__exit:
            message = receiver.fetch()
	  
            routingKeyStr = message.properties['x-amqp-0-10.routing-key']
            routingKey = RoutingKey(routingKeyStr)
            
            print 'Message: ' + routingKey.GetAsString()

            myClass = getProtoClass(routingKey.packageName(), routingKey.messageName())
            msg = myClass()      
            msg.ParseFromString(message.content)
      
            print  'Message count %d' % count
            count += 1
            printMsg(msg)
            
      except MessagingError, m:
         print m
      except KeyboardInterrupt:
        pass
  
      connection.close()         
      
   def exit(self):
      self.__exit = True
      
class Application(Frame):
   def __init__(self, parent):
      Frame.__init__(self, parent)
      self.__parent = parent
      self.__wait = True
      
      self.__receiver = None
      
      self.initUI()

   def initUI(self):
      self.__parent.title("Qpidd Reader")
          
      Label(self, text="Broker info").grid(row=0, sticky=W, padx=5)
      
      frame = Frame(self, borderwidth=2)
      frame.grid(row=1, columnspan=2, sticky=W)
      
      Label(frame, text="IP address:").grid(row=0,padx=4, pady=5)
      self.__txtIp = Entry(frame, borderwidth=2,  width=20)
      self.__txtIp.insert(END, '16.107.161.120')
      self.__txtIp.grid(row=0,column=1,padx=10)
      
      Label(frame, text="Port:").grid(row=0,column=2, padx=10)
      self.__txtPort = Entry(frame, borderwidth=2,  width=10)
      self.__txtPort.insert(END, '62081')
      self.__txtPort.grid(row=0,column=3, padx=10)
      
      Label(self, text="Protocol src").grid(row=2, sticky=W, padx=5, pady=5)
      frame = Frame(self, borderwidth=2)
      frame.grid(row=3, columnspan=2, sticky=W)
      
      self.__txtProtoSrc = Entry(frame, borderwidth=2, width=45)
      self.__txtProtoSrc.insert(END, "/home/cxcai/protos")
      self.__txtProtoSrc.grid(sticky=W, padx=2, pady=2)
      
      self.__btnGet = Button(frame, text=" Start ", command=self.Get)
      self.__btnGet.grid(row=0, column=1)
    
      self.pack(fill=BOTH, expand=1)
      
   def Get(self):
      brokerIp = self.__txtIp.get()
      brokerPort = self.__txtPort.get()
      protoSrc = self.__txtProtoSrc.get()
      
      if self.__wait: # start working here

         self.__receiver = Receiver(brokerIp, brokerPort, protoSrc)
            
         self.__receiver.start()

         self.__wait = False
         self.__btnGet.config(text="Stop")
         self.__parent.config(cursor = "wait")
         self.__btnGet.flash()

      else: # is working, stop it
         self.__receiver.exit()
         self.__receiver.join()

         print "Stopped"
         self.__wait = True
         self.__btnGet.config(text="Start")
         self.__parent.config(cursor = "")
         self.__btnGet.flash()
         
      
def main():
   root = Tk()
   
   app = Application(root)
   root.mainloop()

if __name__ == '__main__':
   main()
   
